﻿using Furion.DependencyInjection;

namespace Admin.NET.Application.Service;

/// <summary>
/// 枚举服务
/// </summary>

[ApiDescriptionSettings(KeepName = true)]
public class BasEnumService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<BasEnum> _rep;
    private readonly SysCacheService _sysCacheService;

    public BasEnumService(SqlSugarRepository<BasEnum> rep, SysCacheService sysCacheService)
    {
        _rep = rep;
        _sysCacheService = sysCacheService;
    }

    //枚举换取逻辑字段

    public async Task<BiJiaoBasEnumReturnDto> BiJiaoBasEnum(BiJiaoBasEnumDto input) {
      var basEnumList = await GetByType(new BasEnumInput { enumType = input.enumType });

        var alogic = basEnumList.Where(t=>t.code==input.aCode).Select(a=>a.logic).FirstOrDefault();
        var blogic = basEnumList.Where(t => t.code == input.bCode).Select(a => a.logic).FirstOrDefault();

        if (alogic.IsNullOrEmpty() || blogic.IsNullOrEmpty()) 
        {
            throw Oops.Oh("请联系运维人员维护"+ input.enumType + "枚举逻辑");
        }

        return new BiJiaoBasEnumReturnDto
        {
            alogic = alogic,
            blogic = blogic
        };
    }



    /// <summary>
    /// 全部
    /// </summary>
    public async Task<List<BasEnum>> All()
    {
        var cacheData = _sysCacheService.Get<List<BasEnum>>(CacheConst.BasEnumList);
        if (cacheData == null || cacheData.Count() <= 0)
        {
            var list = await _rep.Queryable.OrderBy(it => new { it.enumType, it.orderNo })
            .ToListAsync();

            cacheData = list;
            _sysCacheService.Set(CacheConst.BasEnumList, cacheData);
        }

        return cacheData;
    }

    /// <summary>
    /// 通过类型获取
    /// </summary>
    [HttpPost]
    public async Task<List<BasEnum>> GetByType(BasEnumInput input)
    {
        return await _rep.Queryable.Where(it => it.enumType == input.enumType)
            .OrderBy(it => new { it.enumType, it.orderNo })
            .ToListAsync();
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<List<BasEnum>> GetZhanDian()
    {
        return await _rep.Queryable.Where(it => it.enumType == "ZhanDian")
            .OrderBy(it => new { it.enumType, it.orderNo })
            .ToListAsync();
    }

    /// <summary>
    /// 增 
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<BasEnum> Add(BasEnumAddInput input)
    {
        //刷新缓存
        _sysCacheService.Remove(CacheConst.BasEnumList);

        var obj = await _rep.InsertReturnEntityAsync(input.Adapt<BasEnum>());
        return obj;
    }

    /// <summary>
    /// 修改 
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<bool> Update(BasEnumUpdateInput input)
    {
        //刷新缓存
        _sysCacheService.Remove(CacheConst.BasEnumList);
        return await _rep.UpdateAsync(input.Adapt<BasEnum>());
    }
}